const router = require('express').Router()
const { secret } = require('../config')
const { register } = require('../config/schema')
const md5 = require('md5')
const { User } = require('../config/sql')
const jwt = require('jsonwebtoken')
const { wrap } = require('../tool')
const code = require('../tool/code')

router.post('/register', wrap(async (req, res) => {
   const { nickname, password, email, authcode } = req.body
   const { error } = register.validate({ nickname, password, email })
   if (error) throw error.message
   if (!code.has(email, authcode)) throw '323'
   const [data] = await User.findAll({
      attributes: ['email'], 
      where: {
         email
      }
   })
   if (data) throw '324'
   await User.create({
      nickname,
      email,
      password: md5(password)
   })
   const [data0] = await User.findAll({
      attributes: ['uid'],
      where: {
         email
      }
   })
   res.send({
      code: 200,
      msg: '注册成功',
      token: jwt.sign({
         data: {
            account: data0.uid
         }
      }, secret, {
         expiresIn: '7days'
      })
   })
}))
module.exports = router